package com.czkt.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.czkt.pojo.User;
import com.czkt.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@RestController
@CrossOrigin
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    StringRedisTemplate redisTemplate;

    @RequestMapping("/user/list")
    public Object userList(String name, String password) {
        if (name != null && password != null) {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(name != null, User::getUserName, name);
            queryWrapper.lambda().eq(password != null, User::getUserPassword, password);
            List<User> userList = userService.list(queryWrapper);
            Set<Long> uid = userList.stream().map(item -> {
                return item.getUserId();
            }).collect(Collectors.toSet());
            if (!userList.isEmpty()) {
                redisTemplate.opsForValue().set(name, password);
                String uidStr = uid.toString();
                //去除前后[]
                if (uidStr.startsWith("[") && uidStr.endsWith("]")) {
                    uidStr = uidStr.substring(1, uidStr.length() - 1);
                }
                redisTemplate.opsForValue().set("uid", uidStr);
            }
            System.out.println(redisTemplate.opsForValue().get("uid"));
            return userService.list(queryWrapper);
        } else {
            System.out.println("用户名或密码为空");
            return null;
        }
    }

    @RequestMapping("/user/userRoleMenu")
    public Object userRoleMenu(String name) {
        return userService.userRoleMenu(name);
    }
}
